package mo.org.cm309.shoppingcart.utility;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import mo.org.cm309.exception.UploadTypeNotAllowException;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.util.Streams;

public class CommonUtility {
	public static final String ROLE_ADMIN_NAME = "admin";
	public static final String ROLE_CUST_NAME  = "customer";
	
	//USE THIS METHOD TO INSTEAD OF  "req.getParameter" WHEN FORM INCLUDE enctype="multipart/form-data"
	public static HashMap<String, String> getRequestMapping(HttpServletRequest req){
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload();
		
			// Parse the request
			FileItemIterator iter =	upload.getItemIterator(req);
			
			if (iter != null){
				while (iter.hasNext()) {
					FileItemStream item = iter.next();
					String name = item.getFieldName();
				    InputStream stream = item.openStream();
				    if (item.isFormField()) {
				    	map.put(name, Streams.asString(stream));
				    }
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	
	//http://tc.wangchao.net.cn/bbs/detail_68525.html
	public static HashMap getElementByRequest(HttpServletRequest req) throws Exception {
		HashMap map = new HashMap();
		if (req != null) {
			final String[] allowedExt = new String[] { "jpg", "jpeg",
					"gif", "png" };

			// CREATE A DISK FILE FACTORY FOR UPLOAD
			DiskFileItemFactory dfif = new DiskFileItemFactory();
			// SET THE TEMP BUFFER SIZE (4K), OVER SIZE WILL SAVE TO DISK
			// TEMPORARILY
			dfif.setSizeThreshold(4096);
			// ADD A TEMP DIRECTORY REPOSITORY, THE PATH IS ROOT DIRECTORY
			// OF WEB
			dfif.setRepository(new File(""));

			// USE INSTANCE OF DISKFILEITEMFACTORY TO NEW A SERVLET FILE
			// UPLOAD OBJECT
			ServletFileUpload sfu = new ServletFileUpload(dfif);

			List fileList = null;
			fileList = sfu.parseRequest(req);

			// CHECK IF NO ANY IMAGE UPLOAD
			if (fileList == null || fileList.size() == 0) {
				System.out.println("No any field value get from client!");
				return map;
			}

			// GET ALL UPLOAD OBJECT
			Iterator fileItr = fileList.iterator();
			while (fileItr.hasNext()) {
				FileItem fileItem = null;
				String path = null;
				long size = 0;
				fileItem = (FileItem) fileItr.next();
				if (fileItem == null || fileItem.isFormField()) {
					String name = fileItem.getFieldName();
					InputStream stream = fileItem.getInputStream();
					map.put(name, Streams.asString(stream));
					continue;
				}
				// GET THE FULL PATH OF IMAGE
				path = fileItem.getName();
				// GET THE SIZE OF IMAGE
				size = fileItem.getSize();

				if ("".equals(path) || size == 0) {
					System.out
							.println("No any image need to upload or file size is zero!");
					map.put("image", new byte[]{});
					continue;
				}

				// GET THE FILE NAME
				String t_name = path.substring(path.lastIndexOf("\\") + 1);
				// GET THE FILE EXTENSION
				String t_ext = t_name
						.substring(t_name.lastIndexOf(".") + 1);
				// CHECK FILE IS IMAGE TYPE
				int allowFlag = 0;
				int allowedExtCount = allowedExt.length;
				for (; allowFlag < allowedExtCount; allowFlag++) {
					if (allowedExt[allowFlag].equals(t_ext))
						break;
				}
				if (allowFlag == allowedExtCount) {
					throw new UploadTypeNotAllowException("The Type of Upload File is not allowed!");
				}
				map.put(fileItem.getFieldName(), fileItem.get());
			}
		}
		return map;
	}
	
	//IF STRING NOT EQUAL NULL, RETURN THIS STRING
	//IF STRING NOT NULL, RETURN "" (EMPTY STRING);
	public static String getStringNotNull(String s){
		if (s == null)
			return "";
		return s;
	}
	
	//IF STRING NOT EQUAL NULL OR EMPTY, RETURN 0
	//ELSE PARSE STRING TO DOUBLE
	public static double getDoubleByString(String s){
		if ( s!= null && !s.equals(""))
			return Double.parseDouble(s);
		return 0d;
	}
	
	//IF STRING NOT EQUAL NULL OR EMPTY, RETURN 0
	//ELSE PARSE STRING TO INTEGER
	public static int getIntByString(String s){
		if ( s!= null && !s.equals(""))
			return Integer.parseInt(s);
		return 0;
	}
	
	//IF STRING NOT EQUAL NULL OR EMPTY, RETURN 0
	//ELSE PARSE STRING TO INTEGER
	public static long getLongByString(String s){
		if ( s!= null && !s.equals(""))
			return Long.parseLong(s);
		return 0;
	}
}
